﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Reap.Common.Runtime {
	/// <summary>
	/// 引擎单列实例访问
	/// </summary>
	public class EngineContext {
		#region Initializtion Methods
		/// <summary>
		/// 确保方法同步实例化
		/// </summary>
		/// <param name="forceRecreate"></param>
		/// <returns></returns>
		[MethodImpl(MethodImplOptions.Synchronized)]
		public static IEngine Initialize(bool forceRecreate)
		{
			if (Singleton<IEngine>.Instance == null || forceRecreate) //forceRecreate 是否强制重新查找IOC容器
			{
				Singleton<IEngine>.Instance = CreateEngineInstance();
			}
			return Singleton<IEngine>.Instance;
		}
		#endregion

		public static IEngine CreateEngineInstance()
		{
			var typeFinder = new WebAppTypeFinder();
			var engines = typeFinder.FindClassesOfType<IEngine>().ToArray();
			if (engines.Length > 0)
			{
				var defaultEngine =(IEngine)Activator.CreateInstance(engines[0]);
				return defaultEngine;
			}
			else
			{
				throw  new ApplicationException("找不到IOC容器");
			}
		}

		/// <summary>
		/// 获取当前引擎实例化对象
		/// </summary>
		public static IEngine Current
		{
			get
			{
				if (Singleton<IEngine>.Instance == null)
				{
					Initialize(false);
				}
				return Singleton<IEngine>.Instance;
			}
		}
	}
}
